package by.averianov.discounta.webapp.page.create;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.Card;
import by.averianov.discounta.datamodel.CardType;
import by.averianov.discounta.datamodel.UserProfile;
import by.averianov.discounta.datamodel.enums.CardStatus;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.app.BasicAuthenticationSession;
import by.averianov.discounta.webapp.page.BaseLayout;
import by.averianov.discounta.webapp.page.administrator.Administrator;
import by.averianov.discounta.webapp.page.homepage.HomePage;

public class CreateCard extends BaseLayout {

	private static final Logger LOGGER = LoggerFactory.getLogger(CreateCard.class);
	
	private Long id;
	private String cardType;
	private String userProfile;
	private String cardStatus;
	private Long cardDateCreate;
	private Long cardDateStart;
	private UserProfile userEditor;
	private String activateCode;
	
	private UserProfile sessionProfile;
	private String userEditorEmail;
	
	private PageCreator pageCreator;
	
	public CreateCard(Card card, PageCreator pageCreator) {
		super(null);		
		this.pageCreator = pageCreator;
		
		try {
			this.id = card.getId();
			this.cardType = card.getCardType().getNameCardType();			
			this.cardStatus = card.getCardStatus().name();
			this.cardDateCreate = card.getCardDateCreate();
			this.cardDateStart = card.getCardDateStart();
			this.userEditor = card.getUserEditor();
			this.activateCode = card.getActivateCode();
			if(card.getUserProfile() != null) {
				this.userProfile = userService.getUserAccount(card.getUserProfile().getId()).getUserEmail();
			} 			
			LOGGER.debug("Changing a user");
			this.userEditorEmail = userService.getUserAccount(this.userEditor.getId()).getUserEmail();
		} catch (NullPointerException e) {
			LOGGER.debug("Creating a user, card is " + e.getMessage());
			//this.id = null;
			this.cardStatus = CardStatus.cardstatus_inactive.toString();
			this.userEditorEmail = "";
			this.activateCode = userService.randomString(8);
		}
	}
	
	@Inject
	private UserService userService;

	@Override
	protected void onInitialize() {
		super.onInitialize();
		if(BasicAuthenticationSession.get().isSignedIn()) {
			this.sessionProfile = BasicAuthenticationSession.get().getUserProfile();
		} else {
			HomePage page = new HomePage();
			page.error(new ResourceModel("p.error.nouserlogin").getObject());
			setResponsePage(page);			
		}
		LOGGER.debug("Session User From CreatCard: " + sessionProfile);
			
		List<String> cardStatusList = new ArrayList<String>();
        CardStatus[] cardStatusValue = CardStatus.values(); 
        for (CardStatus csv : cardStatusValue) { 
        	cardStatusList.add(csv.name()); 
        } 
        
        List<UserProfile> userProfileList = userService.getAllUserProfile();
        List<String> userEmailList = new ArrayList<String>();
        for (UserProfile uel : userProfileList) {
        	userEmailList.add(userService.getUserAccount(uel.getId()).getUserEmail()); 
        	LOGGER.debug("Add Email to userList: " + userService.getUserAccount(uel.getId()).getUserEmail());
        }
        if(userEmailList.size() == 0) {
        	Administrator page = new Administrator(1, 0L);
			page.error(new ResourceModel("p.error.clearuserbase").getObject());
			setResponsePage(page);
        }        
        
        List<CardType> cardTypeList = userService.getAllCardType();
        List<String> cardTypeNameList = new ArrayList<String>(); 
        for (CardType ctnl : cardTypeList) { 
        	cardTypeNameList.add(ctnl.getNameCardType()); 
        }
        if(cardTypeNameList.size() == 0) {
        	Administrator page = new Administrator(1, 0L);
			page.error(new ResourceModel("p.error.nocardtype").getObject());
			setResponsePage(page);
        }
        
		final Label labelCardId = new Label("labelCardId",  Model.of(id));
		final DropDownChoice<String> cardTypeDropDown = new DropDownChoice<String>("cardType", new PropertyModel<String>(this, "cardType"), cardTypeNameList);
		final DropDownChoice<String> userProfileDropDown = new DropDownChoice<String>("userProfile",  new PropertyModel<String>(this, "userProfile"), userEmailList);
		final DropDownChoice<String> cardStatusDropDown = new DropDownChoice<String>("cardStatus", new PropertyModel<String>(this, "cardStatus"), cardStatusList);
		final Label cardDateCreateText = new Label("cardDateCreate", Model.of(cardDateCreate));
		final Label cardDateStartText = new Label("cardDateStart", Model.of(cardDateStart));		
		final Label userEditorText = new Label("userEditor", Model.of(userEditorEmail));
		final TextField<String> activateCodeText = new TextField<String>("activateCode", Model.of(activateCode));
		
		
		Form<?> form = new Form<Void>("cardCreateForm") {
			@Override
			protected void onSubmit() {
				/*
				PageParameters pageParameters = new PageParameters();
				
				pageParameters.add("cardType", cardTypeDropDown.getModelObject());
				pageParameters.add("userProfile", userProfileDropDown.getModelObject());
				pageParameters.add("cardStatus", cardStatusDropDown.getModelObject());
				pageParameters.add("activateCode", activateCodeText.getModelObject());
				StringValue cardTypeValue = pageParameters.get("cardType");
				StringValue userProfileValue = pageParameters.get("userProfile");
				StringValue cardStatusValue = pageParameters.get("cardStatus");
				StringValue activateCodeValue = pageParameters.get("activateCode");
				*/
		        Card resultingCard = new Card();
		        resultingCard.setId(id);
		        LOGGER.debug("CardType for create Card: " + userService.getCardTypeByName(cardTypeDropDown.getModelObject().toString()).getNameCardType());
		        resultingCard.setCardType(userService.getCardTypeByName(cardTypeDropDown.getModelObject().toString()));
		        
		        //resultingCard.setUserProfile(null);
		        if(userProfileDropDown.getModelObject() != null) {
		        	Long currentId = userService.getAccountByEmail(userProfileDropDown.getModelObject().toString()).getId();
		        	resultingCard.setUserProfile(userService.getUserProfile(currentId));
		        } else {
		        	resultingCard.setUserProfile(null);
		        }
		        
		        resultingCard.setCardStatus(CardStatus.cardstatus_inactive);
		        if(cardStatusDropDown.getModelObject() != null) {
		        	resultingCard.setCardStatus(CardStatus.valueOf(cardStatusDropDown.getModelObject().toString()));
		        }
		        resultingCard.setCardDateCreate(cardDateCreate);
		        if(id == null){
		        	resultingCard.setCardDateCreate(userService.getCurrentDate());
		        }
		        resultingCard.setCardDateStart(cardDateStart);
		        if(cardStatusDropDown.getModelObject().toString() != CardStatus.cardstatus_inactive.toString()){
		        	resultingCard.setCardDateStart(userService.getCurrentDate());
		        }
		        
		        resultingCard.setUserEditor(sessionProfile);
		        
		        resultingCard.setActivateCode(activateCodeText.getModelObject().toString());
		        if(activateCodeText.getModelObject().equals(null)) {
		        	resultingCard.setActivateCode(userService.randomString(8));
		        }
		        
				userService.saveOrUpdateCard(resultingCard);
				setResponsePage(pageCreator.createPage());
			}
		};		 
		add(form);
				
		Label labelCreateCardText = new Label("labelCreateCard", getLabelCreateCard(id));
		form.add(labelCreateCardText);
		
		Label labelCardIdText = new Label("labelCardIdText", getLabelCardIdText());
		if(id == null){
			labelCardIdText = new Label("labelCardIdText", "");
		}
		form.add(labelCardIdText);
		
		
		form.add(labelCardId);		
		form.add(cardTypeDropDown);
		form.add(userProfileDropDown);
		form.add(cardStatusDropDown);
		form.add(cardDateCreateText);
		form.add(cardDateStartText);
		form.add(userEditorText);		
		form.add(activateCodeText);
		
		form.add(new Label("labelSave", getButtonSave()));
		
		Link linkCancel = new Link("linkCancel"){
			@Override
			public void onClick() {
				setResponsePage(pageCreator.createPage());
				
			}
		};
		linkCancel.add(new Label("labelCancel", getButtonCancel()));
		form.add(linkCancel);
	}	

}
